## Apple Provides a OPEN API
## Docs: https://www.apple.com/itunes/affiliates/resources/documentation/itunes-store-web-service-search-api.html
module Shin
  module Play
    class Apple
      
      def new
        self
      end
      
      # Search
      def search(params={})
        # Response
        response = Base.get('https://itunes.apple.com/search?' + URI.encode_www_form(params))
        raise HTTPError, "The response didn't have a 200 HTTP Code. It had #{response.code}." unless response.code == 200
        
        # Data
        data = Oj.load(response.body) rescue nil
        d2 = data['results'] rescue nil
        
        if d2 != nil
          d2.to_hashugar
        else
          raise NotValid, "Couldn't find any responses/results please check again."
        end

      end
      
      # Find
      def find(params={})
        # Response
        response = Base.get('https://itunes.apple.com/lookup?' + URI.encode_www_form(params))
        raise HTTPError, "The response didn't have a 200 HTTP Code. It had #{response.code}." unless response.code == 200
        
        # Data
        data = Oj.load(response.body) rescue nil
        d2 = data['results'] rescue nil
        
        if d2 != nil
          d2.first.to_hashugar
        else
          raise NotValid, "Couldn't find any responses/results please check again."
        end
      end
      
      # Errors
      class NotValid         < StandardError; end
      class MissingArgument  < StandardError; end
      class HTTPError        < StandardError; end
    end
  end
end